package de.mmis.core.base.util;

import java.io.File;
import java.io.IOException;

/**
 * This class contains some utility functions to work with files and folders.
 * 
 * @author Daniel Moos
 */
public final class FileTools {

	/**
	 * Delete the given folder with its content.
	 * 
	 * @param folder
	 *            folder to delete
	 */
	public static void deleteFolder(File folder) {
		if (folder.isDirectory()) {
			for (File content : folder.listFiles())
				FileTools.deleteFolder(content);

			folder.delete();
		} else
			folder.delete();
	}

	/**
	 * Creates a folder at 'java.io.tmpdir'. Note: It's your task to delete this
	 * folder after usage!
	 * 
	 * @return a File handle to the created folder
	 * @throws IOException
	 *             indicates a problem at folder creation
	 */
	public static File tempFolder() throws IOException {
		// http://stackoverflow.com/questions/617414/create-a-temporary-directory-in-java
		File temp;

		temp = File.createTempFile("mmis", null);

		if (temp == null) {
			throw new IOException("Error: Can't create temp file");
		}

		if (!temp.delete()) {
			throw new IOException("Error: Can't delete " + temp.getName());
		}

		if (!temp.mkdir()) {
			throw new IOException("Error: Can't create " + temp.getName());
		}

		return temp;
	}

}
